<?php
namespace Home\Controller;
use Think\Controller;
class ProController extends Controller {
    private $admin_openid='oB_KewRQprjKA4ETYbqcRQgMiBk0';
    private $access_token='';
    public function index(){
    	// 设置选项，包括URL
    	$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . appid . "&redirect_uri=http://nuower.com/index.php/Pro/oauth&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
    	header("Location:".$url);
    }
    public function oauth() {
    	if (isset ( $_GET ['code'] )) {
    		$code = $_GET ['code'];
    		$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . appid . "&secret=" . appsecret . "&code=" . $code . "&grant_type=authorization_code";
    		$output = https_request ( $url );
    		// 第二步
    		if (isset ( $output )) {
    			$jsoninfo = json_decode ( $output, true );
    			$url_info = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $jsoninfo ['access_token'] . "&openid=" . appid . "&lang=zh_CN";
    			$userInfo = https_request ( $url_info );
    		} else {
    			$this->error ( "不好意思,出错了" );
    		}
    		// 第三步
    		if (isset ( $userInfo )) {
    			$res = json_decode ( $userInfo, true );
    			cookie( "openid", $res ['openid'] );
    			cookie( "nickname", $res ['nickname'] );
    			$this->pro_select();
    		} else {
    			$this->error ( "不好意思,出错了" );
    		}
    	} else {
    		$this->error ( "不好意思,出错了" );
    	}
    }


    public function pro_select(){
        $where = array (
                "openid" => $_COOKIE['openid']
        );
        $res = M("order_p")->where($where)->select();


        foreach ($res as $key => $value) {
           $tmp =preg_replace('/\D/s', '', $value['time']);
            $f_time=substr($tmp, 0,12);
           $f_time= date("Y/m/d h:i",strtotime($f_time));
           $f_time= strtotime($f_time);
           $cur_time=time();
           if ($cur_time>$f_time) {
            $data['id']=$value['id'];
            $data['status']=1;
                M("order_p")->save($data);
           }

        }
        
        $this->assign("order",$res);
        //$this->assign("order",$res);
        $this->display("select");
    }




    public function delOrder(){
    	$orderno = I("orderno");
    	$res = substr($orderno,0,1);
    	$tpl = $_SESSION['nickname']."取消订单了"."单号为:". $orderno;
    	//如果是E单，去order表中去删除订单
    	$where = array (
    			/*"openid" => $_COOKIE['openid'],*/
    			"orderno" => $orderno
    	);
    	//0代表以删除订单
    	$status['status'] = '-1';
        $res = M ( 'order_p' )->where ( $where )->save($status); // 
        if ($res) {
        $this->sendtpl_msg($this->admin_openid,$orderno,$tpl);
          //$this->success("取消订单成功",U ( 'Pro/pro_select' ));
            echo '1';
        }
    	
    }

    public function showpo()
    {
        $id=I('get.id');
        $orderinfo = M ( 'order_p' )->find($id);
        $this->assign ( "orderinfo", $orderinfo);
        $this->display();
    }

     //发送模板消息 订单号
    public function sendtpl_msg($touser,$orderno,$first=''){

            $this->access_token=$this->getToken();
        $where['orderno']=$orderno;
        $orderinfo = M ( 'order_p' )->where ( $where )->find(); 
        
    $cost='未知';
//模板消息  
$template=array(
'touser'=>$touser,
'template_id'=>"GrY-eEigqO2iMVwpm4KfO9G8N3FEYx_m004HMD68hXc",
'url'=>"http://nuower.com/index.php/Order/showcarry/orderno/".$orderno,
'topcolor'=>"#7B68EE",
'data'=>array(
'first'=>array('value'=>urlencode($first),'color'=>"#743A3A"),
'orderno'=>array('value'=>urlencode($orderno),'color'=>'#743A3A'),
'amount'=>array('value'=>urlencode($cost),'color'=>'#743A3A'),
'remark'=>array('value'=>urlencode('请查看'),'color'=>'#743A3A'),
)
);

$cus_user=$orderinfo['openid'];

    $content='您已取消订单';

$data = '{
        "touser":"'.$cus_user.'",
        "msgtype":"text",
        "text":
        {
             "content":"'.$content.'"
        }
    }';


$json_template=json_encode($template);

$url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$this->access_token;
$url2 = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$this->access_token;
$res=http_request($url,urldecode($json_template));
$res2=https_post($url2,urldecode($data));

}

public function getToken()
{   
    $data = json_decode(get_php_file("access_token.php"));
    if ($data->expire_time < time()) {
       $json_token=http_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".appid."&secret=".appsecret);
$access_token=json_decode($json_token,true);
//获得access_token
$this->access_token=$access_token['access_token'];
      if ($this->access_token) {
        $data->expire_time = time() + 7000;
        $data->access_token = $this->access_token;
      set_php_file("access_token.php", json_encode($data));
      }
    } else {

     $this->access_token = $data->access_token->access_token;
    }
    return $this->access_token;
    
}


  public function upweixinpic()
  { 
    $otherimages=I('otherimages');
    $data = json_decode(get_php_file("access_token.php"));
if ($data->expire_time < time()) {
       $json_token=http_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".appid."&secret=".appsecret);
$access_token=json_decode($json_token,true);
//获得access_token
$this->access_token=$access_token['access_token'];
      if ($this->access_token) {
        $data->expire_time = time() + 7000;
        $data->access_token =$this->access_token;
        $this->set_php_file("access_token.php", json_encode($data));
      }
    } else {
     $this->access_token = $data->access_token;
    }


//$list = explode(',',$list['otherimages']);
 foreach ($otherimages as $key => $value) {
                            //根据微信JS接口上传了图片,会返回上面写的images.serverId（即media_id），填在下面即可 
   $str = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=".$this->access_token."&media_id=".$value;               
 //获取微信“获取临时素材”接口返回来的内容（即刚上传的图片）  
 $a = file_get_contents($str);  
//$ext=substr(strrchr($a, '.'), 1);

//__DIR__指向当前执行的PHP脚本所在的目录 
$tmp_str= uniqid();
$return_array[]=$tmp_str;
$filenam='weixin/'.$tmp_str.'.jpg';
 //以读写方式打开一个文件，若没有，则自动创建  
 $resource = fopen('./Uploads/'.$filenam , 'w+');  
 //将图片内容写入上述新建的文件  
 fwrite($resource, $a);  
 //关闭资源  
 fclose($resource); 

           }

        $map['id']=I('orderid');
        $f=M('order_p')->where($map)->find();
        if ($f['otherimages']) {
            $arr=unserialize($f['otherimages']);
            $return_array=array_merge($return_array,$arr);
        }
        $save['otherimages']=serialize($return_array);
        $save['upselect']=1;
        $q=M('order_p')->where($map)->save($save);
  
  }


    
}